package morning.cat.study.jdk.serializable;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;

/**
 * 若类不仅实现了Serializable接口，并且还定义了readObject(ObjectInputStream
 * in)和writeObject(ObjectOutputSteam out)，则采用以下方式进行序列化与反序列化：
 * ObjectOutputStream调用User对象的writeObject(ObjectOutputStream out)的方法进行序列化。
 * ObjectInputStream会调用User对象的readObject(ObjectInputStream in)的方法进行反序列化。
 *
 * @author mengzhang6
 * @date 2018/10/22 9:45
 */
public class User2 implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5795046910790072816L;
	private int id;
	private String name;
	private Date addDate;

	public User2() {
	}

	public User2(int id, String name, Date addDate) {
		this.id = id;
		this.name = name;
		this.addDate = addDate;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Date getAddDate() {
		return addDate;
	}

	public void setAddDate(Date addDate) {
		this.addDate = addDate;
	}

	/**
	 * 注意： private void
	 *
	 * @param oos
	 * @throws IOException
	 */
	private void writeObject(ObjectOutputStream oos) throws IOException {
		System.out.println("Serializable writeObject");
		oos.writeObject(id);
		oos.writeObject(name);
		oos.writeObject(addDate);
	}

	private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
		System.out.println("Serializable readObject");
		id = (Integer) ois.readObject();
		name = (String) ois.readObject();
		addDate = (Date) ois.readObject();
	}

	@Override
	public String toString() {
		return "User{" + "id=" + id + ", name='" + name + '\'' + ", addDate=" + addDate + '}';
	}
}
